const express = require('express')
const app = express()

const cors = require('cors')
app.use(cors())

app.use(express.urlencoded({ extended: false }))
app.use(express.json())

//自定义错误
app.use((req, res, next) => {
    res.cc = function (err, status = 1) {
        res.send({
            status,
            err: err instanceof Error ? err.message : err
        })
    }
    next()
})

// //jsonwebtoken
// const config = require('./config')
// const expressJWT = require('express-jwt')
// app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/user\//] }))



//.....................
const userRouter = require('./router/user')
app.use('/user', userRouter)

const songRouter = require('./router/song')
app.use('/song', songRouter)

const videoRouter = require('./router/video')
app.use('/video', videoRouter)

const articleRouter = require('./router/article')
app.use('/article', articleRouter)

const recommendRouter = require('./router/recommend')
app.use('/recommend', recommendRouter)


//验证
const joi = require('joi')
app.use(function (err, req, res, next) {
    // 数据验证失败
    if (err instanceof joi.ValidationError) return res.cc(err)
    res.cc(err)
})
app.use((err, req, res, next) => {
    if (err instanceof joi.ValidationError) return res.cc(err)
    //身份认证失败后的错误
    if (err.name === 'UnauthorizedError') return res.cc('身份认证失败! ')
    res.cc(err)

})

app.listen(2022, () => {
    console.dir("server listening at http://127.0.0.1:2022")
})